package com.code.exam.service.impl;

import com.code.exam.common.content.BaseContext;
import com.code.exam.common.result.PageResult;
import com.code.exam.dto.*;
import com.code.exam.entity.Question;
import com.code.exam.mapper.QuestionMapper;
import com.code.exam.service.QuestionService;
import com.code.exam.vo.EPageResultVO;
import com.code.exam.vo.QPageResultVO;
import com.code.exam.vo.QuestionVO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    QuestionMapper questionMapper;

    public Question addQuestion(QuestionCreateDTO questionCreateDTO) {
        Question question = new Question();
        BeanUtils.copyProperties(questionCreateDTO, question);
        question.setCreatedBy(BaseContext.getCurrentId());
        questionMapper.addQuestion(question);
        return question;
    }

    public Question update(Long questionId, QuestionUpdateDTO questionUpdateDTO) {
        Question question = questionMapper.getById(questionId);
        if (question == null) {
            throw new RuntimeException("试题不存在或无权限修改");
        }
        question.setContent(questionUpdateDTO.getContent());
        question.setOptions(questionUpdateDTO.getOptions());
        question.setAnswer(questionUpdateDTO.getAnswer());
        question.setType(questionUpdateDTO.getType());
        questionMapper.update(question);
        return question;

    }

    public void delete(Long id) {
        //TODO:判断试题是否已被考试引用
        questionMapper.delete(id);
    }

    public PageResult<QPageResultVO> pageQuery(QuestionPageQueryDTO questionPageQueryDTO) {

        //计算offset和limit
        int offset = (questionPageQueryDTO.getPage() - 1) * questionPageQueryDTO.getPageSize();
        int limit = questionPageQueryDTO.getPageSize();

        questionPageQueryDTO.setOffset(offset);
        questionPageQueryDTO.setLimit(limit);

        //查询总数
        Long total = questionMapper.countByCondition(questionPageQueryDTO);


        //查询当前页数据
        List<QPageResultVO> records = questionMapper.selectByCondition(questionPageQueryDTO);


        //封装并返回

        return new PageResult<>(total, questionPageQueryDTO.getPage(), questionPageQueryDTO.getPageSize(),records);
    }

    public Question getDetail(Long id) {
        Question question = questionMapper.getById(id);
            if(question == null){
                throw new RuntimeException("试题不存在");
            }else {
                return question;
            }
    }
}